const jwt = require('jsonwebtoken');
const moment = require('moment');
const jsonParse = require('../lib/jsonParse')
const secret = require('../config/keys')
// token 数据库集合
const Tokens = require('../schemas/users').Tokens;
// 接口集合
const user = require('./model/user')
const dict = require('./model/dict')
const upload = require('./model/upload')
const car = require('./model/car');
const common = require('./model/common');
const stations = require('./model/stations');



module.exports = {
    // 用户接口
    ...user,
    // 字典接口
    ...dict,
    // 上传接口
    ...upload,
    // 车辆
    ...car,
    // 公共接口
    ...common,
    ...stations,
    // 接口不存在
    noHandler: (request, response) => {
        jsonParse.sendResult(response, 404, '接口不存在')
    },
    error: (request, response) => {
        jsonParse.sendResult(response, 404, '接口不存在')
    },
    // 验证Token
    verifyLogin: (request, response, handler, conn) => {
        const authorization = request.headers['Authorization'] || request.headers['authorization']
        if (authorization) {
            const token = authorization.replace('Bearer ', '');
            Tokens.findOne({
                token
            }).then(res => {
                if (res) {
                    jwt.verify(token, secret.secretOrKey, function (err, data) {
                        if (err) {
                            if (err.name == 'TokenExpiredError') {
                                jsonParse.sendResult(response, '-101')
                            } else if (err.name == 'JsonWebTokenError') {
                                jsonParse.sendResult(response, '-102')
                            }
                        } else {
                            // const decodeResult = jwt.decode(token)
                            // let userName = decodeResult.userName
                            handler(request, response, conn)
                        }
                    })
                } else {
                    jsonParse.sendResult(response, '-103')
                }
            })
        } else {
            jsonParse.sendResult(response, '-103')
        }
    }
}